/**
* 
*	WeiXinFilter类
*	作者：邓磊
*	时间：2016年7月4日 16:40:43
*	作用：过滤请求
*	域：无
*
*/

package com.eptok.weixin.filter;

import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.eptok.weixin.util.WxCooikeManager;

import hikefa.core.remote.client.RemoteCall;
import yspos.cpfs.express.entity.ExpUserinfo;
import yspos.cpfs.express.entity.ExpWebchatUserinfo;
import yspos.cpfs.remoteserver.iface.IExpressService;

public class WeiXinFilter implements HandlerInterceptor {

	private IExpressService expressServer = (IExpressService) RemoteCall.getRemoteObject(IExpressService.class);
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest req, 
			HttpServletResponse res, 
			Object arg2) throws Exception {
		String url = getParams(req);
		Object e = WxCooikeManager.getWxUser(req);
		if (null == e) {
			
			String ua = req.getHeader("user-agent");
			//不是微信浏览器
		      if(ua.toLowerCase().indexOf("micromessenger") == -1){
		    	  boolean debug = true;
		    	  if(debug)
		    	  {
		    		  ExpWebchatUserinfo wxUser = expressServer.webchatUserinfoLoad("oEpYqwNb_ownmlIKNPWJ4Mhougjc");
		    		  ExpUserinfo user = expressServer.userinfoGetByopid(wxUser.getOpenId());
		    		  WxCooikeManager.setUser(res, user);
		    		  WxCooikeManager.setWxUser(res, wxUser);
		    		  res.sendRedirect(url);
		    	  }else
		    	  {
		    		  res.sendRedirect(req.getContextPath() + "/toBrowserError.do");//跳转至错误页面
		    	  }
		    	  return false;
		      }
			
			//处理ajax的访问
			String requestWith = req.getHeader("x-requested-with");
			if (requestWith != null && "XMLHttpRequest".equals(requestWith)) {
					res.setHeader("session-status", "timeout");
					res.setContentType("application/json;charset=utf-8");
					res.getWriter().print("{\"msg\":\"未获取到微信用户信息<a href='/"+req.getContextPath()+"/index' target='_top'>退出登录</a>\"}");
			} else {
				String lastUrl = getParams(req);
				lastUrl = URLEncoder.encode(lastUrl,"UTF-8");
				//将lastUrl 写到缓存
				WxCooikeManager.setCookie(res, "lastUrl", lastUrl, 60);
				res.sendRedirect(req.getContextPath() + "/toAutho.do");//跳转至授权界面
			}
			return false;
		}
		String rUrl = req.getRequestURL().toString();
		if(rUrl.indexOf("/user/") != -1){
			ExpUserinfo user = WxCooikeManager.getUser(req);
			if(null == user){
				ExpWebchatUserinfo wxUser = (ExpWebchatUserinfo)e;
				user = expressServer.userinfoGetByopid(wxUser.getOpenId());
				if(user == null)
				{
					res.sendRedirect(req.getContextPath() + "/weixin/toReg.do");
				}else
				{
					WxCooikeManager.setUser(res, user);
				}
				res.sendRedirect(url);
				return false;
			}
		}
		
		return true;
	}
	
	private String getParams(HttpServletRequest req)
	{
		String state = req.getRequestURL()+"";
		Map map = req.getParameterMap();
		for (Object key : map.keySet()) {
			String v = req.getParameter(key.toString());
			if(state.indexOf('?') != -1)
			{
				state += "&"+key.toString()+"="+v;
			}else
			{
				state += "?"+key.toString()+"="+v;
			}
		}
		return state;
		
	}

}

